package sucre

class DocenteController {

    def loginService
    def beforeInterceptor = [action:this.&auth]
    def auth = {
        def result =loginService.validarAcceso(
            session["seguridad_usuario"],
            session["seguridad_funcionesHabilitadas"],
            controllerName,actionName,request.getRemoteAddr().toString())
        if(!result) {
            redirect(controller:"login",action:"auth",params:['acceso':false])
            return false
        }
    }
    def index = {}
    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def parametersService
    def list = {
        params.max = parametersService.getInt("paginacion.maxRegPagina")
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)

        def query={
            if(params.searchField){
                ilike('nombres','%'+params.searchField+'%')
            }
        }
        def docenteList = Docente.createCriteria().list(params,query)
        [ docenteInstanceList:  docenteList,
            docenteInstanceTotal: docenteList.getTotalCount()]
    }
    def create = {
        def docenteInstance = new Docente()
        docenteInstance.properties = params
        def lapsoAc
        if(params.eOc=='edit'){
            docenteInstance=Docente.findById(params.id)
            lapsoAc = docenteInstance.lapsoAcademico
        }else{
            flash.message=''
            params.eOc='create'
            def lapso = sucre.LapsoAcademico.createCriteria()
            def results = lapso.list (max: 1, offset: 0) {
                order("id", "desc")
            }
            println "resul: " + results
            if (!results.isEmpty()){
                lapsoAc = results.get(0).nombre
            }   
        }
        
        docenteInstance.lapsoAcademico = lapsoAc
        return [docenteInstance:docenteInstance,eOc:params.eOc]
    }
    def save = {
        def listaErrores=[]
        def formateador = new java.text.SimpleDateFormat("dd/MM/yyyy")
        if (params.fechaDeNacimiento != null && params.fechaDeNacimiento != "") {
            params.fechaDeNacimiento = formateador.parse(params.fechaDeNacimiento)
        }
        def docenteInstance = new Docente(params)
        if(params.eOc=='edit'){
            println "params.id: " + params.id
            docenteInstance=Docente.get(params.id)
            println  "docenteInstance: " + docenteInstance
            docenteInstance.properties=params
        }
        
        Docente.withTransaction{ status ->
            try{
                if(!docenteInstance.hasErrors() && docenteInstance.save()) {

                    if(params.eOc=='create'){
                        //registrar auditoria def.titular.creado
                        flash.message=message(code:'def.registro.creado',
                            args:[docenteInstance])
                    }else{
                        //def.titular.actualizado
                        flash.message=message(code:'def.registro.actualizado',
                            args:[docenteInstance])
                    }
                        
                    if(params.eOc=='create'){
                        params.eOc='edit'
                    }
                }
            }catch(Exception e){
                println e
                listaErrores.add(message(code:'def.docente.error.Creando'))
                status.setRollbackOnly()
            }
        }
        render(view:'create',model:[docenteInstance:docenteInstance,
                eOc:params.eOc,upd:'si',listaErrores:listaErrores])
    }
    def search={
        redirect(action:list,params:[searchField:params.searchField])
    }
    def delete = {
        def listaErrores=[]
        def docenteInstance = Docente.get(params.id)
        flash.message=message(code:'def.noeliminado', args:[docenteInstance])
        render(view:'create',model:[docenteInstance:new Docente(),upd:'si',
                listaErrores:listaErrores])
    }
}
